<template>
	<el-dialog class="abow-dialog" :visible.sync="visible" :top="playId?'2vh':'5vh'"
		:title="!playId ? '添加短剧' : '修改短剧'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="750px">
		<el-dialog class="innerDialog" v-dialogDrag
		      width="750px"
		      :title="innerTitle+'  '+innerTitleType"
		      :visible.sync="innerCoverVisible"
		      append-to-body @close="innerCloseFn">
			  <div class="d-flex a-cneter j-center pb-20">
				  <el-image :style="{width: '650px',height: '450px'}" :src="clickImg" fit="scale-down"></el-image>
			  </div>
		</el-dialog>
		<el-form  class="form" :model="dataForm" :rules="dataRule" ref="dataForm"  label-width="150px" size="medium" :inline="false"
			labelSuffix="："> 

			

			<el-form-item  prop="name" label="短剧名称">
				<el-input   clearable v-model="dataForm.name" placeholder="短剧名称" />
			</el-form-item>

			<!-- <el-form-item  prop="company" label="公司">
				<el-input   clearable v-model="dataForm.company_name" placeholder="公司名称" />
			</el-form-item> -->
			<!-- <el-form-item prop="company" label="公司">
				<el-select clearable v-model="dataForm.company_value" placeholder="公司名称">
					<el-option v-for="(item,index) in company" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item prop="company" label="公司">
				<el-select clearable v-model="dataForm.company" placeholder="请选择">
					<el-option v-for="(item,index) in companyList" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
	

			<el-form-item prop="cover" label="封面图片">
				<div class="d-flex">
					<img v-if="dataForm.cover" class="d-flex mr-20 pointer" :src="dataForm.cover" @click.stop="lookImg(dataForm.cover,'封面图')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;"
							@click="uploadBtnFn('coverFileBtn','cover')">上传</el-button>
						<input type="file" ref="coverFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images')" />
					</div>
				</div>
			</el-form-item>
			<el-form-item  prop="introduction" label="简介"> 
				<!-- <el-input clearable v-model="dataForm.introduction" placeholder="简介" /> -->
				<Editor  v-if="visible" @event="handleChange" :id="'editor1'" :content="dataForm.introduction" />
			</el-form-item>
			<!-- <el-form-item prop="company" label="支付类型">
				<el-select clearable v-model="dataForm.pay_type" placeholder="请选择">
					<el-option v-for="(item,index) in payType" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item   prop="price" label="售价">
			<!-- 	<el-input type="number" clearable v-model="dataForm.price" placeholder="价格" /> -->
				<Editor v-if="visible" v-model="dataForm.price" @event="handleChange2" id="editor2" :content="dataForm.price" />
			</el-form-item>
			<!-- <el-form-item v-if="playId" prop="last_episode_number" label="最后一集集数">
				<el-input type="number" clearable v-model="dataForm.last_episode_number" placeholder="最后一集集数" />
			</el-form-item> -->
			<!-- <el-form-item v-if="playId" prop="pay_start_cid" label="剧集收费">
				<el-select clearable v-model="dataForm.pay_start_cid" placeholder="请选择">
					<el-option v-for="(item,index) in allEpisodeList" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item> -->
			<!-- <el-form-item v-if="playId" prop="producer" label="制作方">
				<el-input clearable v-model="dataForm.producer" placeholder="制作方" />
			</el-form-item> -->
			<!-- <el-form-item v-if="playId" prop="registration_number" label="剧目备案号">
				<el-input clearable v-model="dataForm.registration_number" placeholder="剧目备案号" />
			</el-form-item> -->
			<!-- <el-form-item v-if="playId" prop="registration_number_url" label="剧目播放授权材料图片">
				<div class="d-flex">
					<img v-if="dataForm.registration_number_url" class="d-flex mr-20 pointer" :src="dataForm.registration_number_url" @click.stop="lookImg(dataForm.registration_number_url,'剧目播放授权材料图')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;"
							@click="uploadBtnFn('registrationFileBtn','registration_number_url')">上传</el-button>
						<input type="file" ref="registrationFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images')" />
					</div>
				</div>
			</el-form-item> -->
			<!-- <el-form-item prop="is_finish" label="是否完结">
				<el-select clearable v-model="dataForm.is_finish" placeholder="请选择">
					<el-option v-for="(item,index) in finish" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item   prop="rank" label="排序">
				<el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" clearable v-model="dataForm.rank"  placeholder="排序" />
				
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<el-select clearable v-model="dataForm.status" placeholder="请选择">
					<el-option v-for="(item,index) in status" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash'
	import {
		isEmail,
		isMobile
	} from '@/libs/validate'
	import schema from 'async-validator'
	import Editor from '../../components/editor/Editor.vue';
	import uploadTools from "./uploadTools";
	export default {
		mixins: [uploadTools],
		components:{
			Editor
		},
		data() {
			return {
				
				playId:null,
				field: '',
				innerTitle:'',
				innerTitleType:'',
				innerCoverVisible:false,
				showimagesProgress: false,
				showvideosProgress: false,
				clickImg:'',
				payType:[
				{
					value:1,
					label:'免费',
				},
				{
					value:2,
					label:'章节付费',
				}],

				
				finish:[
				{
					value:0,
					label:'未完结',
				},
				{
					value:1,
					label:'完结',
				}],
				status:[
				{
					value:0,
					label:'禁用',
				},
				{
					value:1,
					label:'正常',
				}],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				allEpisodeList:[],
				companyList:[],
				company:[
						{
						value:0,
						label:'测试公司',
						},
						{
							value:1,
							label:'测试集团',
						}
					],
				dataForm: {
					name: '', //剧集名称
					cover:'',//封面图片
					introduction:'',//简介
					
					company_value:0,
					// amount:'',//价格
					price:'',
					pay_type:1,//支付类型
					producer:'',//制作方
					is_finish:0,//是否完结，默认0未完结,1完结
					sort:0,//排序
					status: 0, //状态
				}
			}
		},
		created() {},
		mounted() {
			that = this;
		},
		computed: {
			dataRule() {
				return {
					name: [{
							required: true,
							message: '剧集名称不能为空!',
							trigger: ['blur','change']
						}
					],
					company: [{
						required: true,
						message: '公司不能为空!',
						trigger: ['blur','change']
					}],
					cover: [{
							required: true,
							message: '封面图片不能为空!',
							trigger: ['blur','change']
						}
					],
					price: [{
							required: true,
							message: '价格不能为空!',
							trigger: ['blur','change']
						}
					],
					rank: [{
							required: true,
							message: '排序不能为空!',
							trigger: ['blur','change']
						}
					],
					introduction: [{
							required: true,
							message: '简介不能为空!',
							trigger: ['blur','change']
						}
					],
					is_finish: [{
							required: true,
							message: '是否完结不能为空!',
							trigger: ['blur','change']
						}
					],
					status: [{
						required: true,
						message: '状态不能为空!',
						trigger: ['blur','change']
					}]
				}
			}
		},
		watch:{
			'dataForm.pay_type'(newValue){
				if(!this.playId&&newValue==2){
					this.$set(this.dataForm, 'price', '');
				}
			}
		},
		methods: {
			handleChange(data){
				console.log(215,data)
				this.dataForm.introduction = data
			},
			handleChange2(data){
				console.log(215,data)
				this.dataForm.price = data
			},
			innerCloseFn(){
				if(this.$refs.canvas){
					// 清除canvas元素和上下文的引用
					const canvas = this.$refs.canvas;
					const context = canvas.getContext('2d');
					context.clearRect(0, 0, canvas.width, canvas.height);
					// 删除canvas元素的事件监听器
					canvas.removeEventListener('click', this.handleClick);
					// 删除对canvas元素的引用
					canvas.parentNode.removeChild(canvas);
				}
			},
			//获取剧集集数
			async episodeFn(init=true){
				const episodeRes = await this.$axios.get(`/api/playlet/playlet/episodes/${this.playId}`);
				console.log(episodeRes);
				if(Array.isArray(episodeRes)){
					if(episodeRes.length){
						this.allEpisodeList = episodeRes;
						return;
					}
				}
				this.allEpisodeList = [];
			},
			lookImg(clickImg,type) {
				this.clickImg = clickImg;
				this.innerTitleType = type||'';
				this.innerCoverVisible = true;
			},
			async getFiles(event, fileType) {
				this['show' + fileType + 'Progress'] = false;
				console.log(event);
				const files = event.target.files;
				console.log(files);
				if (files.length) {
					const file = files[0];
					let checkRes = false;
					//图片
					if (fileType == 'images') {
						// 压缩图片后再上传
						const reader = new FileReader();
						reader.onload = (e) => {
							const img = new Image();
							img.onload = () => {
								const canvas = document.createElement('canvas');
								const ctx = canvas.getContext('2d');
								const maxWidth = 800; // 压缩后的最大宽度
								const maxHeight = 800; // 压缩后的最大高度
								let width = img.width;
								let height = img.height;
								// 如果宽度和高度超过最大值，则等比例缩放
								if (width > maxWidth || height > maxHeight) {
									const aspectRatio = width / height;
									if (width > height) {
										width = maxWidth;
										height = maxWidth / aspectRatio;
									} else {
										width = maxHeight * aspectRatio;
										height = maxHeight;
									}
								}
								canvas.width = width;
								canvas.height = height;
								ctx.drawImage(img, 0, 0, width, height);
								const compressedDataURL = canvas.toDataURL('image/jpeg',0.9); // 压缩后的图片数据URL，第二个参数表示压缩质量（0-1）
								// 将数据URL转换为Blob对象
								const blob = this.dataURLtoBlob(compressedDataURL);
								// 创建一个新的File对象
								const compressedFile = new File([blob], 'compressed_image.jpg', { type: 'image/jpeg' });
								// 在这里进行后续操作，上传压缩后的图片
								console.log(compressedFile);
								//检查文件格式和大小
								checkRes = this.checkPicFile(compressedFile, 10);
								this.uploadBefore(compressedFile,fileType,checkRes);
							};
							img.src = e.target.result;
						};
						reader.readAsDataURL(file);
					} else if (fileType == 'videos') {
						//视频
						checkRes = this.checkVideoFile(file, 500);
						this.uploadBefore(file,fileType,checkRes);
					}
				}
				event.target.value = '';
			},
			dataURLtoBlob(dataURL) {
				const byteString = atob(dataURL.split(',')[1]);
				const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
				const ab = new ArrayBuffer(byteString.length);
				const ia = new Uint8Array(ab);
				for (let i = 0; i < byteString.length; i++) {
					ia[i] = byteString.charCodeAt(i);
				}
				return new Blob([ab], {
					type: mimeString
				});
			},
			//获取上传密钥和文件路径再上传
			uploadBefore(file,fileType,checkRes){
				if (checkRes) {
					this.$axios.post(`/playlet/sts/uploadPath`, {
						type: fileType
					}).then(stsRes=>{
						if (typeof stsRes == 'object' && stsRes != null) {
							this.createOss(stsRes.token);
							this.handleUpload(file, fileType, stsRes.file_path + stsRes.file_name);
						}else{
							this.$message({
								message: '上传失败！',
								type: 'error',
								duration: 1500
							})
						}
					})
				}
			},
			handleUpload(file,fileType,uploadPath) {
				console.log('handleUploadhandleUpload');
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				console.log(this.client);
				console.log(uploadPath);
				console.log(file);
				this.client.multipartUpload(`${uploadPath}`, file,{
					progress: async function(p) {
						that['show'+fileType+'Progress'] = true;
						that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if(typeof clientRes == 'object' && clientRes!=null){
						if(typeof clientRes.res == 'object' && clientRes.res!=null){
							if(Array.isArray(clientRes.res.requestUrls)){
								if(clientRes.res.requestUrls.length){
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if(!requestUrl){
										return this.$message({
											message: '上传失败！链接为空',
											type: 'error',
											duration: 1500
										})
									}
									if(fileType == 'images'){
										this.$set(this.dataForm, this.field, requestUrl);
									}else if(fileType == 'videos'){
										let video_cover = requestUrl+"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
										console.log(requestUrl);
										this.$set(this.dataForm, this.field, requestUrl);
										console.log(this.dataForm);
										this.videoOptions.video.url = requestUrl;
										this.videoOptions.video.pic = video_cover;
									}
									this.$refs.dataForm.validateField(this.field);
									this['show'+fileType+'Progress'] = false;
									return this.$message({
										message: '上传成功！',
										type: 'success',
										duration: 1500
									})
								}
							}
						}
					}
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err=>{
					console.log(err);
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				this.field = field;
				this.$refs[fileBtn].click();
			},
			init(arr) {
				this.visible = true;
				console.log(465,arr)
				// this.$nextTick(() => {
				// 	console.log('initinitinitinitinitinit');
				// 	this.$refs.dataForm.resetFields();
				// })
				// this.$refs.dataForm.resetFields();
				this.companyList = arr
				console.log(472,this.company)
				let obj = {
					name: '', //剧集名称
					cover:'',//封面图片
					introduction:'',//简介
					// amount:'',//价格
					price:'',
					company:null,
					pay_type:1,//支付类型
					producer:'',//制作方
					is_finish:0,//是否完结，默认0未完结,1完结
					rank:1,
					status: 0 //状态
				}
				this.dataForm = obj;
				console.log(432,obj)
				this.$refs.dataForm.resetFields();
			},
			update(row,arr) {
			
				console.log(415,row)
				this.companyList = arr
				console.log(494,this.companyList)
				let copyObj = JSON.parse(JSON.stringify(row))
				copyObj.company = copyObj.company_id
				if(copyObj.company==0){
					copyObj.company = null
				}
				this.dataForm = copyObj;
				this.visible = true;
				// this.episodeFn();
				// this.$nextTick(() => {
				// 	// this.$refs.dataForm.resetFields();
				// 		console.log(426,row)
				// 	this.dataForm = Object.assign({}, row);
				// 	// this.dataForm = row
				// 	console.log(this.dataForm);
				// })
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交',this.dataForm);
				let dataForm = this.dataForm
				dataForm.rank = Number(dataForm.rank)
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(525,dataForm);
					dataForm.company_id = dataForm.company;
					console.log(431,dataForm.introduction);
					this.$axios.post(this.playId?`/api/playlet/playlet/update/${this.playId}`:'/api/playlet/playlet/create', dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1200,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}).catch(() => {})
				})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form{
		width: 640px;
	}
	.innerDialog :deep(.el-dialog__header){
		padding: 20px!important;
	}
	.innerDialog :deep(.el-dialog__body){
		padding: 0px!important;
	}
	.innerDialog :deep(.el-dialog__headerbtn){
		font-size: 25px!important;
	}
</style>